﻿/*
    Copyright (c) 2007 - 2009, Carlos Guzmán Álvarez

    All rights reserved.

    Redistribution and use in source and binary forms, with or without modification, 
    are permitted provided that the following conditions are met:

        * Redistributions of source code must retain the above copyright notice, 
          this list of conditions and the following disclaimer.
        * Redistributions in binary form must reproduce the above copyright notice, 
          this list of conditions and the following disclaimer in the documentation and/or 
          other materials provided with the distribution.
        * Neither the name of the author nor the names of its contributors may be used to endorse or 
          promote products derived from this software without specific prior written permission.

    THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
    "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
    LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
    A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
    CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
    EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
    PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
    PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
    LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
    NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
    SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

using System;
using System.Collections;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Collections.Specialized;
using System.Linq;
using System.Threading;
using System.Windows.Threading;
using Framework.Net.Xmpp.Core;
using Framework.Net.Xmpp.Serialization.InstantMessaging.Client;
using Framework.Net.Xmpp.Serialization.InstantMessaging.Client.Presence;
using Framework.Net.Xmpp.Serialization.InstantMessaging.Roster;

namespace Framework.Net.Xmpp.InstantMessaging
{
    /// <summary>
    /// Contact's Roster
    /// </summary>
    public sealed class XmppRoster : IEnumerable<XmppContact>, INotifyCollectionChanged
    {
        #region · INotifyCollectionChanged Members ·

        public event NotifyCollectionChangedEventHandler CollectionChanged;

        #endregion

        #region · Events ·

        /// <summary>
        /// Occurs when the presence of a contact changes
        /// </summary>
        public event EventHandler ContactPresenceChanged;

        /// <summary>
        /// Occurs when the Contact's Roster is recevied
        /// </summary>
        public event EventHandler RosterReceived;

        #endregion

        #region · Fields ·

        private ObservableCollection<XmppContact>   contacts;
        private XmppSession                         session;
        private XmppConnection                      connection;
        private List<string>                        pendingMessages;
        private Dispatcher                          dispatcher;
        private AutoResetEvent                      rosterReceived;

        #endregion

        #region · Indexers ·

        /// <summary>
        /// Gets the contact with the given JID
        /// </summary>
        /// <param name="jid"></param>
        /// <returns></returns>
        public XmppContact this[string jid]
        {
            get
            {
                return this.contacts.Where(contact => contact.ContactId.BareIdentifier == jid).SingleOrDefault();
            }
        }

        #endregion
       
        #region · Constructors ·

        /// <summary>
        /// Initializes a new instance of the <see cref="XmppSession"/> class
        /// </summary>
        internal XmppRoster(XmppSession session)
        {
            this.session            = session;
            this.connection         = session.Connection;
            this.dispatcher         = Dispatcher.CurrentDispatcher;
            this.contacts           = new ObservableCollection<XmppContact>();
            this.pendingMessages    = new List<string>();
            this.rosterReceived     = new AutoResetEvent(false);

            this.session.StateChanged += new EventHandler<XmppSessionStateChangedEventArgs>(OnSessionStateChanged);
        }

        #endregion

        #region · Methods ·

        /// <summary>
        /// Adds the given contact to the roster
        /// </summary>
        /// <param name="jid">Contact JID</param>
        /// <param name="name">Contact name</param>
        public void AddContact(string jid, string name)
        {
            //<iq type='set'
            //    from='romeo@montague.lit/orchard'
            //    id='roster1'>
            //  <query xmlns='jabber:iq:roster'>
            //    <item jid='aim.shakespeare.lit' name='AIM Gateway'/>
            //  </query>
            //</iq>
            RosterQuery query   = new RosterQuery();
            IQ          iq      = new IQ();

            iq.ID   = XmppIdentifierGenerator.Generate();
            iq.Type = IQType.Set;
            iq.From = this.connection.UserId.ToString();

            RosterItem item = new RosterItem();

            item.Subscription   = RosterSubscriptionType.None;
            item.Jid            = jid;
            item.Name           = name;

            query.Items.Add(item);

            iq.Items.Add(query);

            this.pendingMessages.Add(iq.ID);

            this.connection.Send(iq);
        }

        /// <summary>
        /// Deletes a user from the roster list
        /// </summary>
        public void RemoveContact(string jid)
        {
            this.RemoveContact(new XmppJid(jid));
        }

        /// <summary>
        /// Deletes a user from the roster list
        /// </summary>
        public void RemoveContact(XmppJid jid)
        {
            //<iq from='juliet@example.com/balcony' type='set' id='roster_4'>
            //  <query xmlns='jabber:iq:roster'>
            //    <item jid='nurse@example.com' subscription='remove'/>
            //  </query>
            //</iq>
            RosterQuery query = new RosterQuery();
            IQ iq = new IQ();

            iq.ID   = XmppIdentifierGenerator.Generate();
            iq.Type = IQType.Set;
            iq.From = this.connection.UserId.ToString();

            RosterItem item = new RosterItem();

            item.Jid            = jid.BareIdentifier.ToString();
            item.Subscription   = RosterSubscriptionType.Remove;

            query.Items.Add(item);

            iq.Items.Add(query);

            this.pendingMessages.Add(iq.ID);

            this.connection.Send(iq);
        }

        /// <summary>
        /// Request Roster list to the XMPP Server
        /// </summary>
        public void RequestRosterList()
        {
            RosterQuery query = new RosterQuery();
            IQ iq = new IQ();

            iq.ID = XmppIdentifierGenerator.Generate();
            iq.Type = IQType.Get;
            iq.From = this.connection.UserId.ToString();

            iq.Items.Add(query);

            this.connection.Send(iq);

            this.rosterReceived.WaitOne();
        }

        #endregion

        #region · Internal Methods ·

        /// <summary>
        /// Called when the presence of a contact is changed
        /// </summary>
        internal void OnContactPresenceChanged()
        {
            if (this.ContactPresenceChanged != null)
            {
                this.ContactPresenceChanged(this, EventArgs.Empty);
            }
        }

        #endregion

        #region · IEnumerable<XmppContact> Members ·

        IEnumerator<XmppContact> IEnumerable<XmppContact>.GetEnumerator()
        {
            return this.contacts.GetEnumerator();
        }

        #endregion

        #region · IEnumerable Members ·

        public IEnumerator GetEnumerator()
        {
            return this.contacts.GetEnumerator();
        }

        #endregion

        #region · Event Wiring ·

        private void WireEvents()
        {
            this.contacts.CollectionChanged         += new NotifyCollectionChangedEventHandler(OnCollectionChanged);
            this.connection.PresenceMessageReceived += new EventHandler<XmppPresenceMessageReceivedEventArgs>(OnPresenceMessageReceived);
            this.connection.RosterMessageReceived   += new EventHandler<XmppRosterNotificationEventArgs>(OnRosterNotification);
            this.connection.QueryErrorReceived      += new EventHandler<XmppQueryErrorReceivedEventArgs>(OnQueryErrorReceived);
        }

        private void UnwireEvents()
        {
            this.contacts.CollectionChanged         -= new NotifyCollectionChangedEventHandler(OnCollectionChanged);
            this.connection.PresenceMessageReceived -= new EventHandler<XmppPresenceMessageReceivedEventArgs>(OnPresenceMessageReceived);
            this.connection.RosterMessageReceived   -= new EventHandler<XmppRosterNotificationEventArgs>(OnRosterNotification);
            this.connection.QueryErrorReceived      -= new EventHandler<XmppQueryErrorReceivedEventArgs>(OnQueryErrorReceived);
        }

        #endregion

        #region · Event Handlers ·

        private void OnPresenceMessageReceived(object sender, XmppPresenceMessageReceivedEventArgs e)
        {
            XmppJid     jid     = new XmppJid(e.Presence.From);
            XmppContact contact = this[jid.BareIdentifier];

            if (e.Presence.TypeSpecified && e.Presence.Type == PresenceType.Subscribe) 
            {
                this.session.Presence.Subscribed(jid);
            }
            else if (contact != null)
            {
                contact.UpdatePresence(jid, e.Presence);
            }
        }

        private void OnRosterNotification(object sender, XmppRosterNotificationEventArgs e)
        {
            // It's a roster management related message
            foreach (RosterItem item in e.RosterQuery.Items)
            {
                XmppContact contact = this.Where(c => c.ContactId.BareIdentifier == item.Jid).FirstOrDefault();
                
                if (contact == null)
                {
                    // Create the new contact
                    XmppContact newContact = new XmppContact(
                        this.session,
                        item.Jid,
                        item.Name,
                        (XmppContactSubscriptionType)item.Subscription,
                        item.Groups);

                    // Add the contact to the roster
                    this.contacts.Add(newContact);
                }
                else
                {
                    // Update contact data
                    contact.RefreshData(
                        item.Name,
                        (XmppContactSubscriptionType)item.Subscription,
                        item.Groups);
                }
            }

            if (this.RosterReceived != null)
            {
                this.RosterReceived(this, new EventArgs());
            }

            this.rosterReceived.Set();
        }

        private void OnQueryErrorReceived(object sender, XmppQueryErrorReceivedEventArgs e)
        {
            if (this.pendingMessages.Contains(e.IQError.ID))
            {
                this.pendingMessages.Remove(e.IQError.ID);
            }

            this.rosterReceived.Set();
        }

        private void OnSessionStateChanged(object sender, XmppSessionStateChangedEventArgs e)
        {
            if (e.NewState == XmppSessionState.LoggingIn)
            {
                this.WireEvents();
            }
            else if (e.NewState == XmppSessionState.LoggingOut)
            {
                this.UnwireEvents();
                this.contacts.Clear();
            }
        }

        #endregion

        #region · Change Notification ·

        private void OnCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
        {
            this.dispatcher.BeginInvoke(
                DispatcherPriority.ApplicationIdle,
                new ThreadStart(delegate
                {
                    if (this.CollectionChanged != null)
                    {
                        this.CollectionChanged(this, e);
                    }
                }));
        }

        #endregion
    }
}
